package puc.redes.tarea3.client;

import java.awt.GridBagConstraints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URLEncoder;
import java.net.UnknownHostException;

import javax.swing.ButtonGroup;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.WindowConstants;

import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.Syntax;



public class SparqlClient extends JFrame {

	private JTextArea queryTextArea;

	private JTextField textField;
	private final ButtonGroup buttonGroup = new ButtonGroup();

	public SparqlClient() {
		initComponents();
		System.out.println("hello");
	}

	public void initComponents() {
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		setTitle("SPARQL Client");

		queryTextArea = new JTextArea();

		textField = new JTextField();
		textField.setColumns(10);

		JButton btnSendQuery = new JButton("Query");

		JRadioButton rdbtnHttpGet = new JRadioButton("HTTP GET");
		rdbtnHttpGet.setSelected(true);
		buttonGroup.add(rdbtnHttpGet);

		JRadioButton rdbtnHttpPost = new JRadioButton("HTTP POST");
		buttonGroup.add(rdbtnHttpPost);

		GroupLayout layout = new GroupLayout(getContentPane());
		layout.setHorizontalGroup(layout
				.createParallelGroup(Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addGroup(
										layout.createParallelGroup(
												Alignment.LEADING)
												.addGroup(
														layout.createSequentialGroup()
																.addGap(90)
																.addGroup(
																		layout.createParallelGroup(
																				Alignment.TRAILING)
																				.addComponent(
																						textField,
																						Alignment.LEADING,
																						263,
																						263,
																						263)
																				.addComponent(
																						queryTextArea,
																						Alignment.LEADING,
																						GroupLayout.DEFAULT_SIZE,
																						263,
																						Short.MAX_VALUE)
																				.addGroup(
																						layout.createSequentialGroup()
																								.addComponent(
																										rdbtnHttpGet)
																								.addPreferredGap(
																										ComponentPlacement.RELATED,
																										72,
																										Short.MAX_VALUE)
																								.addComponent(
																										rdbtnHttpPost))))
												.addGroup(
														layout.createSequentialGroup()
																.addGap(181)
																.addComponent(
																		btnSendQuery)))
								.addGap(95)));
		layout.setVerticalGroup(layout.createParallelGroup(Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addGap(19)
								.addComponent(textField,
										GroupLayout.PREFERRED_SIZE,
										GroupLayout.DEFAULT_SIZE,
										GroupLayout.PREFERRED_SIZE)
								.addPreferredGap(ComponentPlacement.RELATED)
								.addComponent(queryTextArea,
										GroupLayout.PREFERRED_SIZE, 153,
										GroupLayout.PREFERRED_SIZE)
								.addPreferredGap(ComponentPlacement.UNRELATED)
								.addComponent(btnSendQuery)
								.addPreferredGap(ComponentPlacement.UNRELATED)
								.addGroup(
										layout.createParallelGroup(
												Alignment.BASELINE)
												.addComponent(rdbtnHttpPost)
												.addComponent(rdbtnHttpGet))
								.addContainerGap(12, Short.MAX_VALUE)));
		btnSendQuery.addActionListener(new queryButtonListener(queryTextArea,
				textField, buttonGroup,rdbtnHttpGet, rdbtnHttpPost));
		getContentPane().setLayout(layout);

		// Add Components to this panel.
		GridBagConstraints c = new GridBagConstraints();
		c.gridwidth = GridBagConstraints.REMAINDER;

		c.fill = GridBagConstraints.HORIZONTAL;
		add(textField, c);

		c.fill = GridBagConstraints.BOTH;
		c.weightx = 1.0;
		c.weighty = 1.0;
		pack();
	}

	class queryButtonListener implements ActionListener {
		JTextArea mqueryTextArea;
		JTextField mEndpointTextField;
		JRadioButton mGetButton;
		JRadioButton mPostButton;

		public queryButtonListener(JTextArea textArea,
				JTextField endpointTextField, ButtonGroup buttonGroup, JRadioButton rdbtnHttpGet, JRadioButton rdbtnHttpPost) {
			mqueryTextArea = textArea;
			mEndpointTextField = endpointTextField;
			mGetButton = rdbtnHttpGet;
			mPostButton = rdbtnHttpPost;
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			if (e.getSource() instanceof javax.swing.JButton) {
				if (((javax.swing.JButton) e.getSource()).getLabel().equals("Query")) {
					String query = mqueryTextArea.getText();
					String url = mEndpointTextField.getText();
					
					// add client code here
					
					Query q=QueryFactory.create();
			        Socket s = null;
			         String str="select distinct ?Concept where {[] a ?Concept} LIMIT 100";//=q.toString(Syntax.syntaxSPARQL );
			         System.out.println(str);
			        try 
			        {
			        	String foot ="&format=text%2Fhtml&timeout=0&debug=on";
			        	str=URLEncoder.encode(str,"UTF-8") ;
			        	
			            String host = "localhost";
			            String file = "/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=";

			            
			            String qu=URLEncoder.encode(file +str+foot,"ASCII") ;
			            System.out.println(qu);
			            System.out.println(URLEncoder.encode(qu,"UTF-8"));
			            System.out.println(file +str+foot);
			            
			            
			            
			            int port = 100;
			        
			            s = new Socket(host, port);
	
			            OutputStream out =  s.getOutputStream();
			            PrintWriter outw = new PrintWriter(out, false);
			            
			
			            outw.print("GET " + file +str+foot+ " HTTP/1.1\r\n");
			            outw.print("Host: "+host+"\r\n");
			            outw.print("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n");
			            //outw.print("select distinct ?Concept where {[] a ?Concept} LIMIT 100\r\n");
			            outw.print("\r\n");
			            outw.flush();
	
			            InputStream in = s.getInputStream();
			            DataInputStream flujo = new DataInputStream( in );
			            
			            
			            
			            InputStreamReader inr = new InputStreamReader(in);
			            BufferedReader br = new BufferedReader(inr);
			            String line;
			            while ((line = br.readLine()) != null) 
			            {
			                    System.out.println(line);
			            }
			             br.close();          // Q. Do I need this?
			             
			             
									        } 
			        catch (UnknownHostException e1) {
			        	 System.out.println("Unknown Host exception");
			        } 
			        catch (IOException e1) {
			        	System.out.println("IO exception");
			        }
	
			            if (s != null)
			            {
			                    try
			                    {	
			                            s.close();
			                    }
			                    catch ( IOException ioEx ) {}
			            }
			      }		
			}
		}
	}

	public static void main(String args[]) {
		// Schedule a job for the event dispatch thread:
		// creating and showing this application's GUI.
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				// Turn off metal's use of bold fonts
				UIManager.put("swing.boldMetal", Boolean.FALSE);
				new SparqlClient().setVisible(true);
			}
		});
	}
}
